package com.example.agent_springai.contoller;

import com.example.agent_springai.system.QueryCondition;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/ai")
public class ServiceController {

    private final ChatClient serviceChatClient;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final String IMAGE_URL_PREFIX = "https://mdn.alipayobjects.com/one_clip/afts/img/";

    // 工具方法：创建文本响应
    private Map<String, Object> createTextResp(Object content) {
        Map<String, Object> textResp = new HashMap<>();
        textResp.put("type", "text");
        textResp.put("content", content != null ? content.toString() : "");
        return textResp;
    }

    // 处理「花卉问题」
    private Flux<Map<String, Object>> handleFlower(QueryCondition condition, String prompt, String chatId) {
        Map<String, Object> flowerReq = new HashMap<>();
        flowerReq.put("message", prompt);
        flowerReq.put("session_id", chatId);
        flowerReq.put("response_type", "text");

        Map<String, Object> flowerResp = new HashMap<>();
        flowerResp.put("type", "flower_problem");
        flowerResp.put("api_url", "http://localhost:5002/chat");
        flowerResp.put("request_data", flowerReq);
        flowerResp.put("message", "花卉问题已转发专用助手");
        return Flux.just(flowerResp);
    }

    @RequestMapping(value = "/service", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<Map<String, Object>> chat(@RequestParam String prompt, @RequestParam String chatId) {

        /*// 1. 解析LLM返回的查询条件
        String analysisPrompt = MenuPrompt.AnalysisPrompt
                .replace("{user_prompt}", prompt)
                .replace("{today}", MenuPrompt.today);*/

        return serviceChatClient.prompt()
                .user(prompt)
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content()
                .map((Object content) -> {  // 显式指定content为Object类型

                    // 处理空内容
                    if (content == null) {
                        return createTextResp("");
                    }

                    // 处理Map类型
                    if (content instanceof Map) {
                        Map<String, Object> contentMap = (Map<String, Object>) content;
                        if (contentMap.containsKey("type") && contentMap.containsKey("data")) {
                            Map<String, Object> chartResp = new HashMap<>();
                            chartResp.put("type", "chartData");
                            chartResp.put("chartData", contentMap);
                            log.debug("LLM返回的图表数据: {}", contentMap);
                            return chartResp;
                        }
                        return createTextResp(content);
                    }

                    // 处理String类型
                    if (content instanceof String) {
                        String contentStr = (String) content;
                        if (contentStr.contains(IMAGE_URL_PREFIX)) {
                            Map<String, Object> chartResp = new HashMap<>();
                            chartResp.put("type", "chartUrl");
                            chartResp.put("url", contentStr.trim());
                            return chartResp;
                        }
                        return createTextResp(contentStr);
                    }

                    // 其他类型按文本处理
                    return createTextResp(content.toString());
                });
        }
}